// pages/couple/detail.js
const app = getApp()

Page({
  data: {
    coupleInfo: null,      // 情侣信息
    isLoaded: false,       // 数据加载状态
    isUnbinding: false     // 解绑中状态
  },

  // 加载情侣数据
  loadCoupleInfo() {
    this.setData({ isLoaded: false })
    
    if (app.globalData.coupleInfo) {
      this.setData({
        coupleInfo: app.globalData.coupleInfo,
        isLoaded: true
      })
    } else {
      this.setData({ isLoaded: true })
    }
  },

  // 监听全局数据变化
  watchGlobalData() {
    if (this._globalDataWatcher) return
    
    this._globalDataWatcher = app.watchGlobalData({
      coupleInfo: (newVal) => {
        this.setData({
          coupleInfo: newVal,
          isLoaded: true
        })
      }
    })
  },

  onLoad() {
    this.watchGlobalData()
    this.loadCoupleInfo()
  },

  onShow() {
    // 每次页面显示时刷新数据
    this.loadCoupleInfo()
  },

  onUnload() {
    if (this._globalDataWatcher) {
      this._globalDataWatcher()
      this._globalDataWatcher = null
    }
  },

  // 解绑情侣关系
  unbindCouple() {
    wx.showModal({
      title: '确认解绑',
      content: '确定要解除情侣关系吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({ isUnbinding: true })
          
          if (app.devConfig.enabled) {
            // 开发模式：模拟解绑
            setTimeout(() => {
              app.saveCouple(null)
              this.setData({ isUnbinding: false })
              wx.showToast({ title: '已解除绑定' })
              setTimeout(() => wx.navigateBack(), 1000)
            }, 800)
          } else {
            // 生产环境：调用API解绑
            const coupleService = require('../../services/couple')
            coupleService.unbindCouple().then(() => {
              app.saveCouple(null)
              this.setData({ isUnbinding: false })
              wx.showToast({ title: '已解除绑定' })
              setTimeout(() => wx.navigateBack(), 1000)
            }).catch(err => {
              this.setData({ isUnbinding: false })
              wx.showToast({ title: err.message || '解绑失败', icon: 'none' })
            })
          }
        }
      }
    })
  },

  // 返回上一页
  onBack() {
    wx.navigateBack()
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '我们的情侣空间',
      path: '/pages/couple/detail',
      imageUrl: this.data.coupleInfo?.shareImage || '/assets/images/couple-share.jpg'
    }
  }
})